import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
from iteration5_user_management.query_user import UserQuery

class UserDeleter:
    def __init__(self):
        self.db = Database()
        self.query = UserQuery()
    
    def delete_user(self, user_id):
        """
        删除用户
        
        参数:
            user_id (int): 用户ID
        
        返回:
            bool: 删除成功返回True，否则返回False
        """
        try:
            # 检查用户是否存在
            user = self.query.query_user_by_id(user_id)
            if not user:
                print(f"错误：ID为 {user_id} 的用户不存在")
                return False
            
            # 连接数据库并执行删除
            self.db.connect()
            
            self.db.cursor.execute(
                "DELETE FROM user WHERE id = ?",
                (user_id,)
            )
            self.db.conn.commit()
            
            if self.db.cursor.rowcount > 0:
                print(f"成功：用户 {user[1]} 已删除")
                return True
            else:
                print("警告：没有记录被删除")
                return False
        except Exception as e:
            print(f"错误：删除用户时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def delete_users(self, user_ids):
        """
        批量删除用户
        
        参数:
            user_ids (list): 用户ID列表
        
        返回:
            tuple: (成功删除数量, 总数量)
        """
        success_count = 0
        total_count = len(user_ids)
        
        for user_id in user_ids:
            if self.delete_user(user_id):
                success_count += 1
        
        return success_count, total_count

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    deleter = UserDeleter()
    query = UserQuery()
    
    print("===== 用户删除 =====")
    print("1. 删除单个用户")
    print("2. 批量删除用户")
    
    choice = input("请选择操作 (1-2): ")
    
    # 先查询所有用户
    users = query.query_all_users()
    if not users:
        print("没有找到任何用户信息")
        sys.exit(0)
    
    print("\n当前用户列表:")
    print("ID\t用户名\t角色\t姓名\t联系方式\t状态")
    for user in users:
        print(f"{user[0]}\t{user[1]}\t{user[2]}\t{user[3] or '-'}\t{user[4] or '-'}\t{user[5]}")
    
    if choice == '1':
        try:
            user_id = int(input("\n请输入要删除的用户ID: "))
            deleter.delete_user(user_id)
        except ValueError:
            print("错误：用户ID必须是数字")
    
    elif choice == '2':
        ids_input = input("\n请输入要删除的用户ID，多个ID用逗号分隔: ")
        try:
            user_ids = [int(id.strip()) for id in ids_input.split(',')]
            success_count, total_count = deleter.delete_users(user_ids)
            print(f"\n批量删除完成：成功 {success_count}/{total_count}")
        except ValueError:
            print("错误：ID必须是数字")
    
    else:
        print("无效的选择")